<template>
  <van-tabbar v-model="active" style="z-index: 999" v-if="show">
    <van-tabbar-item
      v-for="(tab, index) in tabbar"
      :icon="tab.icon"
      :to="tab.path"
      :dot="tab.dot"
      :key="index"
      :class="tab.class"
    >{{tab.name}}</van-tabbar-item>
    <div
      class="cart_num"
      v-if="cartNum > 0"
      :style="{left: cartLeft}"
      @click="$router.push({name: 'cart'})"
    >
      <b>{{cartNum}}</b>
    </div>
  </van-tabbar>
</template>

<script>
import { Tabbar, TabbarItem } from "vant";
import { CART_TOTAL } from "@/api/shop";

export default {
  data() {
    return {
      active: 0,
      tabbar: [
        {
          name: "精选",
          path: "/",
          pathName: "home",
          icon: "compass-full",
          dot: false
        },
        {
          name: "分类",
          path: "/items",
          pathName: "class",
          icon: "class-full",
          dot: false
        },
        {
          name: "",
          path: "/order",
          pathName: "cart",
          icon: "cart",
          dot: false,
          class: "tabbar_cart",
          ref: "cart"
        },
        {
          name: "订单",
          path: "/user/order/list/0",
          pathName: "user-order-list",
          icon: "daifahuo",
          dot: false
        },
        {
          name: "我的",
          path: "/user",
          pathName: "user",
          icon: "wode",
          dot: false
        }
      ],
      cartNum: 0,
      show: true
    };
  },

  computed: {
    cartLeft() {
      const clientW = document.documentElement.clientWidth;
      const left = clientW / 2 - (this.cartNum > 9 ? 8 : 4);
      return left + "px";
    }
  },

  watch: {
    $route: "changeActive"
  },

  created() {
    const toName = this.$route.name;
    this.setActive(toName);
    //5.24切换店铺购物车数量改变
    this.$reqGet(CART_TOTAL, {
      teamid: this.user.teamid,
      memberId: this.user.id
    })
      .then(res => {
        this.cartNum = res.data.data;
      })
      .catch(res => {});
    window.tabbar = this;
  },

  methods: {
    changeActive({ name }) {
      this.setActive(name);
    },
    setActive(name) {
      this.tabbar.forEach((tab, i) => {
        if (tab.pathName == name) {
          this.active = i;
          return false;
        }
      });
    },
    // click(tab) {
    //   console.log('路径')
    //   console.log(this.$route.path)
    //   if (tab === "精选" && this.$route.name=="xiaolu") {
    //     // window.location.href = "src/views/home";
    //     this.$router.push({name:"home"})
    //   }
    // }
  },

  components: {
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem
  }
};
</script>

<style lang="scss" scoped>
.cart_num {
  position: absolute;
  bottom: 32px;
  left: 49%;
  text-align: center;
  color: white;
  font-size: 16px;
  z-index: 2000;
}
</style>

